package com.bobi.tfca.web.security;

import com.bobi.tfca.model.constant.exception.SysMessageConsts;
import com.bobi.tfca.utils.ChineseUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录认证过滤器,从json中获取用户名和密码
 */
public class LoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {


    private final ObjectMapper mapper = new ObjectMapper();

    public LoginAuthenticationFilter() {
    }

    /**
     * 从json中获取用户名和密码，校验验证码
     * @param request 请求
     * @param response 响应
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        String contentType = request.getContentType();
        if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
            try {
                JsonNode body = mapper.readTree(request.getReader());
                String telephone = body.get("telephone").asText();
                String password = body.get("password").asText();
                // 校验密码是不是中文
                if (ChineseUtils.containsChinese(password)) {
                    throw new BadCredentialsException(SysMessageConsts.USER_PWD_IS_UTF8);
                }
                // 认证 用户名密码认证令牌
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(telephone, password);
                // 设置详细信息
                this.setDetails(request, authRequest);
                // 身份验证
                return this.getAuthenticationManager().authenticate(authRequest);
            } catch (Exception e) {
                throw new BadCredentialsException(e.getMessage(), e);
            }
        }
        return super.attemptAuthentication(request, response);
    }

}
